'use strict';
const db = uniCloud.database()
const role = 0 //0为管理员，10为工作人员
exports.main = async (event, context) => {
	//event为客户端上传的参数
	// console.log('客户端上传的参数 : ', event)
	const collection = db.collection('user')
	//执行鉴权 获得标准响应体 和 调用接口的用户资料
	let {
		res,
		user
	} = await cheak(event);
	//响应体 code<=1111时，执行客户端的请求。否则直接返回获得的 响应体；
	if (res.code <= 1111) {
		let test = await md5_vm_test()
		if (test) {
			const res_ord = await collection.orderBy("_id", "desc").get()
			// console.log('服务器查询结果 : ', res_ord);
			// let res = {
			// 	success: false,
			// 	message: '请联系管理员'
			// };
			if (res_ord.data) {
				let ord_group = res_ord.data
				for (let i = 0; i < ord_group.length; i++) {
					if (ord_group[i].name == event.data.name) {
						res.success = false
						res.message = '此账号已经存在'

						// console.log('此账号已经存在 : ', event.name);
						//返回数据给客户端
						return res
					}
				}
				let md5_password = await hex_md5(event.data.password)
				event.data.password = md5_password
				res.data = await collection.add(event.data)

				res.success = true
				res.message = '保存成功'

				// console.log('此账号已经保存 : ', event.name);
				//返回数据给客户端
				return res

			} else {
				res.success = false;
				res.success = '密码加密出现问题，请联系管理员';
			}

		}


	}
	return res



}

async function cheak(e) {
	var res = {
		"code": "0000",
		"data": {}
	}
	console.log(e)
	var user = await db.collection('user').where({
		'_id': e.uid,
		'token': e.token
	}).get()
	console.log(user)
	user = user.data[0];
	if (user) { //登录正常
		//校验token 是否过期；是否失效 ----暂不开发后续云函数支持互调后开发
		//生成token 随机数+时间戳+uid
		var timestamp = (new Date()).valueOf(); //获取当前毫秒的时间戳
		let str_token = Math.floor(Math.random() * 10000) + user._id + timestamp;
		let tok_tim = timestamp - user.token_time //token存在了多长时间
		if (tok_tim < 86400000) { //小于24小时,执行操作

			//code码,正常
			res.code = '0000'

			//判断是否需要更新
			if (tok_tim > 82800000) { //小于1小时,执行操作
				//将token写入数据集
				db.collection('user').where({
					name: user.name,
					// password: event.data.password
				}).update({
					token: str_token,
					token_time: timestamp
				});
				res.token = str_token
				res.code = '1111'
			}
		}
		if (role != user.role) {
			res.code = 4003
		}
	} else {
		res.code = 4001;
	}
	return {
		res,
		user
	}
}
/*------这里我只保留了hex_md5加密----------------------
 * RSA数据安全公司的JavaScript实现。MD5消息
 *摘要算法，定义在RFC 1321。
 * 2.1版本版权(C) Paul Johnston 1999 - 2002
 *其他贡献者:Greg Holt, Andrew Kepert, Ydnar, Lostinet
 *在BSD许可下发布
 *更多信息见http://pajhome.org.uk/crypt/md5。
 */

/*
 *可配置变量。您可能需要调整这些以与之兼容
 *服务器端，但默认的工作在大多数情况下。
 */
const hexcase = 0; /* 十六进制格式输出。0-小写;1-大写        */
const b64pad = ""; /* base - 64填充字符。“=”表示严格遵守RFC   */
const chrsz = 8; /* 每个输入字符的位数。8-ASCII;16- Unicode      */
/*
 *这些是你通常想要调用的函数
 *它们接受字符串参数并返回十六进制或base-64编码的字符串
 */
async function hex_md5(s) {
	let str2binl_ok = await str2binl(s);
	let core_md5_ok = await core_md5(str2binl_ok, s.length * chrsz);
	let binl2hex_ok = await binl2hex(core_md5_ok);
	return binl2hex_ok;
}
/*
 *执行一个简单的自我测试，看看VM是否工作
 */
async function md5_vm_test() {
	let hex_md5_ok = await hex_md5("abc");
	return hex_md5_ok == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * 计算一组小端字的MD5和一个位长度
 */
async function core_md5(x, len) {
	/* append padding */
	x[len >> 5] |= 0x80 << ((len) % 32);
	x[(((len + 64) >>> 9) << 4) + 14] = len;

	var a = 1732584193;
	var b = -271733879;
	var c = -1732584194;
	var d = 271733878;

	for (var i = 0; i < x.length; i += 16) {
		var olda = a;
		var oldb = b;
		var oldc = c;
		var oldd = d;

		a = await md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
		d = await md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
		c = await md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
		b = await md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
		a = await md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
		d = await md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
		c = await md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
		b = await md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
		a = await md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
		d = await md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
		c = await md5_ff(c, d, a, b, x[i + 10], 17, -42063);
		b = await md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
		a = await md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
		d = await md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
		c = await md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
		b = await md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);

		a = await md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
		d = await md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
		c = await md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
		b = await md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
		a = await md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
		d = await md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
		c = await md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
		b = await md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
		a = await md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
		d = await md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
		c = await md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
		b = await md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
		a = await md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
		d = await md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
		c = await md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
		b = await md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);

		a = await md5_hh(a, b, c, d, x[i + 5], 4, -378558);
		d = await md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
		c = await md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
		b = await md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
		a = await md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
		d = await md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
		c = await md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
		b = await md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
		a = await md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
		d = await md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
		c = await md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
		b = await md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
		a = await md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
		d = await md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
		c = await md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
		b = await md5_hh(b, c, d, a, x[i + 2], 23, -995338651);

		a = await md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
		d = await md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
		c = await md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
		b = await md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
		a = await md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
		d = await md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
		c = await md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
		b = await md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
		a = await md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
		d = await md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
		c = await md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
		b = await md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
		a = await md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
		d = await md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
		c = await md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
		b = await md5_ii(b, c, d, a, x[i + 9], 21, -343485551);

		a = await safe_add(a, olda);
		b = await safe_add(b, oldb);
		c = await safe_add(c, oldc);
		d = await safe_add(d, oldd);
	}
	return Array(a, b, c, d);

}

/*
 * 这些函数实现了算法使用的四个基本操作。
 */
async function md5_cmn(q, a, b, x, s, t) {
	return await safe_add(await bit_rol(await safe_add(await safe_add(a, q), await safe_add(x, t)), s), b);
}
async function md5_ff(a, b, c, d, x, s, t) {
	return await md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
async function md5_gg(a, b, c, d, x, s, t) {
	return await md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
async function md5_hh(a, b, c, d, x, s, t) {
	return await md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
async function md5_ii(a, b, c, d, x, s, t) {
	return await md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}


/*
 * 加上整数，包装为2^32。这在内部使用16位操作
 *解决一些JS解释器的bug。
 */
async function safe_add(x, y) {
	var lsw = (x & 0xFFFF) + (y & 0xFFFF);
	var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
	return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * 按位向左旋转32位数字。
 */
async function bit_rol(num, cnt) {
	return (num << cnt) | (num >>> (32 - cnt));
}


/*
 *将字符串转换为小端字节的单词数组
 *如果chrsz是ASCII，字符>255的hi字节将被忽略。
 */
async function str2binl(str) {
	var bin = Array();
	var mask = (1 << chrsz) - 1;
	for (var i = 0; i < str.length * chrsz; i += chrsz)
		bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);
	return bin;
}

/*
 * 将一个小端字数组转换为十六进制字符串。
 */
async function binl2hex(binarray) {
	var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
	var str = "";
	for (var i = 0; i < binarray.length * 4; i++) {
		str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +
			hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF);
	}
	return str;
}
